import axios from 'axios'
import store from '@/vuex'


axios.defaults.baseURL = 'http://127.0.0.1:8080'
if (store.getters.getToken) {
  axios.defaults.headers.common['token'] = store.getters.getToken
}


import {
	Loading,
	Message,
	MessageBox
} from 'element-ui'
export default {
	get(url, callback, params = {}) {
		const loading = Loading.service({
			lock: true,
			text: '数据加载中',
			spinner: 'el-icon-loading',
			background: 'rgba(255, 255, 255, 0.7)'
		})
		axios.get(url, {
			params: params
		}).then(response => {
			if (response.data.meta.code === 200) {
				callback(response.data.message)
			} else {
				Message.error(response.data.meta.msg)
			}
		}).catch(err => {
			Message.error(err)
		}).finally(() => {
			loading.close()
		})
	},
	post(url, callback, params = {}, msg) {
		const formData = new FormData()
		for (let key in params) {
			formData.append(key, params[key])
		}
		const loading = Loading.service({
			lock: true,
			text: '数据提交中',
			spinner: 'el-icon-loading',
			background: 'rgba(255, 255, 255, 0.7)'
		})
		setTimeout(() => {
			loading.close()
		}, 10000)
		axios.post(url, formData)
			.then(response => {
				if (response.data.meta.code === 200) {

					if (msg === undefined) {
						Message.success(response.data.meta.msg)
					} else if (msg != null && msg.length != 0) {
						Message.success(msg)
					}
					callback(response.data.message)
				} else {
					Message.error(response.data.meta.msg)
				}
			}).catch(err => {
				Message.error(err)
			}).finally(() => {
				loading.close()
			})
	},


	/**
	 * 将登录成功的 token放到header中,便于每一次 请求你的时候 携带token
	 * @param {Object} token
	 */
	setToken(token) {
		axios.defaults.headers.common['token'] = token
	}
}
